package com.gudy.counter.service.impl;

import com.gudy.counter.bean.Account;
import com.gudy.counter.bean.CounterRes;
import com.gudy.counter.cache.RedisStringCache;
import com.gudy.counter.enumutil.CacheType;
import com.gudy.counter.service.AccountSerivce;
import com.gudy.counter.thirdpaet.uuid.GudyUuid;
import com.gudy.counter.util.ConstCommon;
import com.gudy.counter.util.DBUtil;
import com.gudy.counter.util.JsonUtil;
import com.gudy.counter.util.TimeformatUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.concurrent.TimeUnit;

@Service
public class AccountServiceImpl implements AccountSerivce {
    @Autowired
    DBUtil dbUtil;

    @Override
    public Account login(long uid, String password, String captcha, String captchaId) throws Exception {
        //交易入参的合法性
        if (StringUtils.isEmpty(password) || StringUtils.isEmpty(captcha) || StringUtils.isEmpty(captchaId)){
            return null;
        }
        //校验验证码,获取到生成的验证码
        String captchCache = RedisStringCache.queryCache(captchaId, CacheType.CAPTCHA);
        if (StringUtils.isEmpty(captchCache)){
            return null;
        }else if (!(StringUtils.pathEquals(captcha,captchCache))){
            return null;
        }
        RedisStringCache.removeCache(captchaId,CacheType.CAPTCHA);
        //对比数据库用户登录
        Account account = DBUtil.quertAccount(uid, password);
        if (account == null){
            return null;
        }
        account.setToken(String.valueOf(GudyUuid.getInstance().getUUID()));
        RedisStringCache.saveCache(account.getToken(), JsonUtil.toJson(account),CacheType.ACCOUNT);
        //更新登录时间
        Date curDate = new Date();
        new DBUtil().updateLoginTime(uid, TimeformatUtil.yyyyMMdd(curDate),TimeformatUtil.hhMMss(curDate));
        return account;
    }

    @Override
    public boolean checkAccountExisInCache(String token) {
        if (StringUtils.isEmpty(token)){
            return false;
        }
        String acc = RedisStringCache.queryCache(token, CacheType.ACCOUNT);
        if (StringUtils.isEmpty(acc)){
            return false;
        }
        RedisStringCache.saveCache(token,acc,CacheType.ACCOUNT);
        return true;
    }

    @Override
    public boolean logout(String token) {
        RedisStringCache.removeCache(token,CacheType.ACCOUNT);
        return true;
    }

    @Override
    public CounterRes updatePassword(long uid, String oldPassword, String newPassword) {
        boolean updateState = dbUtil.updatePassword(uid, oldPassword, newPassword);
        if (updateState){
            return new CounterRes(ConstCommon.SUCCESS,"修改成功",null);
        }
        return new CounterRes(ConstCommon.FALA,"修改失败",null);
    }
}
